package cn.myfirefly.moming.common.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.stereotype.Repository;

import cn.myfirefly.moming.common.entity.MMDataDict;
import cn.myfirefly.moming.common.model.DataDictFilterDto;
import cn.myfirefly.core.BaseDao;
import cn.myfirefly.core.model.PageResultDto;
import cn.myfirefly.utils.FilterUtil;

@Repository
public class DataDictItemDao extends BaseDao<MMDataDict>{
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public PageResultDto<MMDataDict> getList(DataDictFilterDto dto, String dataTypeItem) {
		Session session = sessionFactory.getCurrentSession();
		PageResultDto<MMDataDict> resultDto = new PageResultDto<>();
		
		StringBuffer countSql = new StringBuffer("select count(r) from MMDataDict r where r.dataType = ? ");
		StringBuffer querySql = new StringBuffer("from MMDataDict r where r.dataType = ? ");
		
		List paramList = new ArrayList();
		paramList.add(dataTypeItem);
		FilterUtil.handleFilterSql(dto, "r", countSql, querySql, paramList);
		
		Query query = session.createQuery(countSql.toString());
		FilterUtil.setQueryParams(query, paramList);
		Number number = (Number)query.uniqueResult();
		resultDto.setTotal(number.intValue());
		if (number.intValue() > 0) {
			query = session.createQuery(querySql.toString());
			FilterUtil.setQueryParams(query, paramList);
			List<MMDataDict> list = query
					.setFirstResult((dto.getPageCurrent() - 1) * dto.getPageSize())
					.setMaxResults(dto.getPageSize())
					.list();
			resultDto.setPageCurrent(dto.getPageCurrent());
			resultDto.setList(list);
		}
		return resultDto;
	}
	
	public long countByDataType(String dataType) {
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createSQLQuery(" SELECT COUNT(1) FROM mm_data_dict dd WHERE dd.data_type = ? ");
		query.setParameter(0, dataType);
		Number number = (Number) query.uniqueResult();
		return number.longValue();
	}
	
}	
